import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

// 引入路由组件
import routes from "@/router/routes";

// 引入store
import store from "@/store";

// 重写push和replace
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originPush.call(this, location, resolve, reject);
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject);
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

let router = new VueRouter({
  // 配置路由
  routes,
  // 添加路由滚动行为
  scrollBehavior() {
    return { y: 0 };
  },
});

router.beforeEach(async (to, from, next) => {
  let token = store.state.user.token;
  let name = store.state.user.userInfo.name;
  // 如果已经登录
  if (token) {
    // 登录了，如果还想去登录和注册，拒绝
    if (to.path === "/login" || to.path === "/register") {
      next(false);
    } else {
      // 登录了去的不是login，如果有用户信息
      if (name) {
        next();
      } else {
        // 如果没有用户信息就获取信息
        try {
          await store.dispatch("getUserInfo");
          next();
        } catch (error) {
          // 清除token
          await store.dispatch("userLogout");
          next("/login");
        }
      }
    }
  } else {
    // 没有登录
    // 如果去交易相关、支付相关、个人中心相关的组件时会跳转到登录组件
    if (
      to.path.indexOf("/trade") !== -1 ||
      to.path.indexOf("/pay") !== -1 ||
      to.path.indexOf("/paysuccess") !== -1 ||
      to.path.indexOf("/center") !== -1
    ) {
      next(`/login?redirect=${to.path}`);
    } else {
      next();
    }
  }
});

export default router;
